package com.clever.mall.service.impl;

import com.clever.mall.commons.dto.DiscountRequestParam;
import com.clever.mall.entity.DisReUser;
import com.clever.mall.entity.Discount;
import com.clever.mall.mapper.DisReUserMapper;
import com.clever.mall.mapper.DiscountMapper;
import com.clever.mall.service.DiscountService;
import com.clever.mall.utils.MyBeanUtils;
import com.clever.mall.vo.DiscountVo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class DiscountServiceImpl implements DiscountService {
    @Resource
    DiscountMapper discountMapper;
    @Resource
    DisReUserMapper disReUserMapper;

    //以关键字查询一类的红包
    @Override
    public List<DiscountVo> findByWord(String msg) {
        List<Discount> discounts = discountMapper.selectByWord(msg);
        List<DiscountVo> discountVos = MyBeanUtils.copyListProperties(discounts, DiscountVo::new);
        return discountVos;
    }

    //判断客户是否已经拥有此种优惠券1.有就增加数量2.无就创建关联
    @Override
    public int add(List<DiscountRequestParam> list) {
        int insert=0;
        for (DiscountRequestParam p : list) {
            //查询当前用户是否已有此种优惠券
            DisReUser disReUser = findByUserIdAndDisId(1, p.getDiscountId());
            if (disReUser == null){
                //在第三方表中穿点关联，表示领取到新类型的券
                DisReUser creat = new DisReUser(1, p.getDiscountId(), p.getSum());
                insert = disReUserMapper.insert(creat);
            }else {
                //更新该券的数量
                disReUser.setSum(disReUser.getSum()+p.getSum());
                insert = disReUserMapper.update(disReUser);
            }
        }
        return insert;
    }

    //查询当前用户的此种优惠券
    @Override
    public DisReUser findByUserIdAndDisId(int userId, int disId) {
        DisReUser disReUser = disReUserMapper.findByUserIdAndDisId(userId, disId);
        return disReUser;
    }

    //更改用户优惠券的数量
    @Override
    public int update(DisReUser disReUser) {
        int update = disReUserMapper.update(disReUser);
        return update;
    }
}
